package com.monitor.zk.zookeeper.handle;

import core.Request;
import com.monitor.zk.zookeeper.core.RequestEnum;
import core.annotation.HandleProcess;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
/**
 * 异步添加到发送队列中
 * 为发送的数据做开始准备
 * 目前只根据type来新增数据，来给service做区分
 */
public class PrepareHandleProcess extends Thread implements HandleProcess {

    private HandleProcess next;
    public static RUN_STATUS STATUS = RUN_STATUS.STOP;
    private LinkedBlockingQueue<Request> workQueue = new LinkedBlockingQueue();

    public PrepareHandleProcess(HandleProcess next){
        super(new HandleThreadGroup("prepareSend"),"PrepareHandleProcess");
        this.next = next;
    }

    @Override
    public void run() {
        while (true){
            if(STATUS == RUN_STATUS.RUN){
                try {
                    Request request = workQueue.take();
                    if(request.getRequestType() == 0){
                        throw new NullPointerException("Request type is null");
                    }
                    switch (request.getRequestType()){
                        case RequestEnum.VMINFO:
                            request.getBody().put("type","vm");
                            break;
                        case RequestEnum.LINUXINFP:
                            request.getBody().put("type","linux");
                            break;
                        case RequestEnum.PROJECTINFO:
                            request.getBody().put("type","project");
                            break;
                        default:
                            throw new IllegalStateException("Unexpected value: " + request.getRequestType());
                    }
                    next.exec(request);
                } catch (InterruptedException e) {
                    log.error(e.getMessage());
                } catch (NullPointerException e){
                    log.error(e.getMessage());
                } catch (IllegalStateException e){
                    log.error(e.getMessage());
                }
            }else{
                log.warn("prepareHandle未启动！");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void exec(Request request) {
        workQueue.add(request);
    }

}
